﻿using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System.Drawing;
using System.Text;

namespace DocMark;



public class DocumentMark
{
    public event Action<string>? ProcessMsgEvent;

    public async Task<bool> MarkAsync(MarkSetting setting)
    {
        ProcessMsgEvent?.Invoke(SimpleLog.Log($"工作目录：{FileTool.RootPath}"));
        string orignPath = FileTool.GetFilePath("orign.docx");
        string targetPath = FileTool.GetFilePath("target.docx");
        string markPath = FileTool.GetFilePath($"target_mark_{setting.MarkColor.Name}.docx");
        WordHandler wordHanler = new();
        IMarkLister markLister = wordHanler;
        switch (setting.FileType)
        {
            case FileType.Pdf:
                ProcessMsgEvent?.Invoke(SimpleLog.Log($"目标 <pdf>"));
                orignPath = FileTool.GetFilePath("orign.pdf");
                markLister = new PdfHandler();
                markLister.HandleMsg += (msg) =>
                {
                    ProcessMsgEvent?.Invoke(msg);
                };
                wordHanler.HandleMsg += (msg) =>
                {
                    ProcessMsgEvent?.Invoke(msg);
                };
                break;
            case FileType.Docx:
                ProcessMsgEvent?.Invoke(SimpleLog.Log($"目标 <docx>"));
                wordHanler.HandleMsg += (msg) =>
                {
                    ProcessMsgEvent?.Invoke(msg);
                };
                break;
        }

        if (!File.Exists(orignPath) || !File.Exists(targetPath))
        {
            ProcessMsgEvent?.Invoke((SimpleLog.Error($"请确认存在以下文件\n{orignPath} \n{targetPath} ！")));
            return false;
        }
        try
        {
            List<string> marks = await markLister.GetTextAsync(orignPath, setting.OrignColor);
            ProcessMsgEvent?.Invoke(SimpleLog.Log("查找标记完成"));
            bool ret = await wordHanler.MarkAsync(targetPath, markPath, marks, setting.MarkColor);
            ProcessMsgEvent?.Invoke(SimpleLog.Log("标记完成"));
            return ret;
        }
        catch (Exception ex)
        {
            ProcessMsgEvent?.Invoke(SimpleLog.Error(ex.Message));
            return false;
        }
    }
}
